package com.yxuan.springboot.util;


import java.util.*;

/**
 * 用于生成11位永不从重复的数字，将生成的数字存入set集合防止重复，将数据库中的set集合进行修改
 */
public class UniqueNumberGenerator {


    private static final int MAX_NUMBER = 999999999; // 最大的9位数
    private static final int MIN_NUMBER = 100000000; // 最小的9位数
    private static final int NUMBER_LENGTH = 11; // 数字长度

    //获取数据库中的set集合
    //private static Set<Integer> usedNumbers = new HashSet<>();


    public static int generateUniqueNumber() {

        HashMap<String, Object> map = new HashMap<>();

        Random random = new Random();
        int number = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
        int uniqueNumber = number * 10 + getCheckDigit(number);

        return Math.abs(uniqueNumber);
    }

    private static int getCheckDigit(int number) {
        int sum = 0;
        int factor = 2;
        for (int i = NUMBER_LENGTH - 2; i >= 0; i--) {
            int digit = (number / (int) Math.pow(10, i)) % 10;
            sum += digit * factor;
            factor = factor == 7 ? 2 : factor + 1;
        }
        int remainder = sum % 11;
        return remainder == 0 ? 0 : 11 - remainder;
    }


}
